package com.voice.call.service.impl;

import java.io.File;
import java.net.InetAddress;
import java.util.Properties;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse;
import com.voice.call.common.Const;
import com.voice.call.service.IpQueryService;

@Service
public class IpQueryServiceImpl implements IpQueryService{
	
	private static final Logger log = LoggerFactory.getLogger(IpQueryServiceImpl.class);
	
	private static final String ip_file = "ip_country.mmdb";
	
	@Resource
	private Properties configProperties;

	@Override
	public String getIsoCodeForIp(String ip){
		
		try {
			
			String path = configProperties.getProperty(Const.UPLOAD_SAVE_PATH) + ip_file;
			
			File database = new File(path);
			DatabaseReader reader = new DatabaseReader.Builder(database).build();
			InetAddress ipAddress = InetAddress.getByName(ip);
			CountryResponse resp = reader.country(ipAddress);
			
			//log.info("json = {}",resp.toJson());
			return resp.getCountry().getIsoCode();
			//log.info("json = {}",resp.getCountry().getIsoCode());
			//log.info("json = {}",resp.getCountry().getName());
			//log.info("json = {}",resp.getCountry().getNames().get("zh-CN"));
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("ip获取iso code发生异常");
			return null;
		}
		
	}
	
	@Override
	public CountryResponse  getIpFoResponse(String ip) {
       try {
			
			String path = configProperties.getProperty(Const.UPLOAD_SAVE_PATH) + ip_file;
			
			File database = new File(path);
			DatabaseReader reader = new DatabaseReader.Builder(database).build();
			InetAddress ipAddress = InetAddress.getByName(ip);
			CountryResponse resp = reader.country(ipAddress);
			return resp;
			//log.info("json = {}",resp.getCountry().getIsoCode());
			//log.info("json = {}",resp.getCountry().getName());
			//log.info("json = {}",resp.getCountry().getNames().get("zh-CN"));
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error("ip获取iso code发生异常");
			return null;
		}
	}
}
